package com.bw.utils;

import com.bw.bean.CustomerConsumption;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.sql.Timestamp;
import java.util.Random;

public class ConsumptionSource implements SourceFunction<CustomerConsumption> {
    private boolean isRunning = true;
    private final Random random = new Random();
    private final String[] paymentMethods = {"微信支付", "支付宝", "银行卡", "现金"};
    private final String[] goodsTypes = {"食品", "服装", "电子产品", "化妆品", "家居用品", "其他"};

    @Override
    public void run(SourceContext<CustomerConsumption> ctx) throws Exception {
        long recordId = 1L;
        while (isRunning) {
            CustomerConsumption consumption = new CustomerConsumption();
            consumption.setRecordId(recordId++);
            consumption.setCustomerId((long) (1 + random.nextInt(100))); // 1-100的客户ID
            consumption.setShopId((long) (1 + random.nextInt(10))); // 1-10的店铺ID
            consumption.setAmount(50 + random.nextDouble() * 1000); // 50-1050元的消费金额
            consumption.setConsumeTime(new Timestamp(System.currentTimeMillis() - random.nextInt(24 * 3600 * 1000 * 7)));
            consumption.setPaymentMethod(paymentMethods[random.nextInt(paymentMethods.length)]);
            consumption.setGoodsType(goodsTypes[random.nextInt(goodsTypes.length)]);

            ctx.collect(consumption);

            // 控制数据生成速度
            Thread.sleep(50);

            // 生成500条消费记录后停止
            if (recordId > 500) {
                break;
            }
        }
    }

    @Override
    public void cancel() {
        isRunning = false;
    }
}